/**
 * 路线制定信息业务逻辑处理接口实现类
 * @author zqd	差旅小组
 *
 * 上午10:08:52
 */
package com.cbts.service.travel.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.cbts.dao.BusinessTravelDao;
import com.cbts.dao.BusinessTravelListDao;
import com.cbts.dao.TravelStandardDao;
import com.cbts.dao.UserInfoDao;
import com.cbts.entity.BusinessTravel;
import com.cbts.entity.BusinessTravelList;
import com.cbts.entity.TravelStandard;
import com.cbts.service.travel.RoutesetService;
import com.cbts.util.Page;

public class RoutesetServiceImpl implements RoutesetService {
	protected BusinessTravelDao businessTravelDao;
	protected BusinessTravelListDao businessTravelListDao;
	protected UserInfoDao userInfoDao;
	protected TravelStandardDao travelStandardDao;
	
	
	public void setBusinessTravelDao(BusinessTravelDao businessTravelDao) {
		this.businessTravelDao = businessTravelDao;
	}
	public void setBusinessTravelListDao(BusinessTravelListDao businessTravelListDao) {
		this.businessTravelListDao = businessTravelListDao;
	}
	public void setUserInfoDao(UserInfoDao userInfoDao) {
		this.userInfoDao = userInfoDao;
	}
	public void setTravelStandardDao(TravelStandardDao travelStandardDao) {
		this.travelStandardDao = travelStandardDao;
	}
	
	

	/* 
	 * @see com.cbts.service.travel.RoutesetService#alterRoute(java.util.List, java.lang.String, java.lang.String, java.util.Date, java.util.Date)
	 */
	public boolean alterRoute(List<BusinessTravel> btlist, String travelOrder,
			String userid, int standardId, Date startTime, Date endTime) {
		// zqd 下午09:19:40
		//修改路线
		try{
			businessTravelDao.deleteByTravelOrder(travelOrder);		//将原来的businesstravel清除
			BusinessTravelList list=businessTravelListDao.get(travelOrder);
			TravelStandard ts=travelStandardDao.get(standardId);
			Double amount=0.0;
			
			//计算
			Double pperkm=ts.getTraffic().getPrice();				//每公里价格
			Double pperday=ts.getHotel().getPrice();				//每天的住宿费
			Double mealscost=ts.getMealsCost();
			Double elsecost=ts.getElseCost();
			for(BusinessTravel l: btlist){
				l.setSum(pperkm*l.getDistance()+pperday*l.getTime()+mealscost*l.getTime()+elsecost*l.getTime());	//计算该段的钱，运输费+住宿费+饮食费+其他费用
				amount+=l.getSum();						//总数增加
				l.setUserInfo(userInfoDao.get(userid));	//这里也要设定员工的信息
				l.setTravelStandard(ts);				//设定差旅标准信息
				l.setBusinessTravelList(list);			//设定travelOrder
			}
			
			list.setAmount(amount);						//修改总费用
			list.setStartTime(startTime);
			list.setEndTime(endTime);
			list.setVerifierStatus("待审核");			//将状态改为待审核
			businessTravelListDao.update(list);			//将原来的list更新
			
			businessTravelDao.saveList(btlist);			//将数据插入到数据库,提交路线
			
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}

	
	/* 
	 * @see com.cbts.service.travel.RoutesetService#getAllBusinessTravelList(java.lang.String)
	 */
	public Page<BusinessTravelList> getPendingBusinessTravelList(String userid) {
		// zqd 上午08:48:10
		//获得该员工所有的BusinessTravelList
		return businessTravelListDao.findByProperty("and o.userInfoByUserid.userid = ? and (o.verifierStatus = '待审核' " +
				"or o.verifierStatus = '审核不通过')",
				new Object[]{userid}, -1, -1);
	}
	/* 
	 * @see com.cbts.service.travel.RoutesetService#getBusinessTravelInfo(java.lang.String, java.lang.String)
	 */
	public Page<BusinessTravel> getBusinessTravelInfo(String travelorder,
			String userid) {
		// zqd 上午08:48:10
		//查找传入travelorder的所有BusinessTravel,即该出差列表的所有出差信息
		return businessTravelDao.findByProperty("and o.businessTravelList.travelOrder = ?",
				new Object[]{travelorder}, -1, -1);
	}
	/* 
	 * @see com.cbts.service.travel.RoutesetService#getBusinessTravelListByOrder(java.lang.String, java.lang.String)
	 */
	public BusinessTravelList getBusinessTravelListByOrder(String travelorder,
			String userid) {
		// zqd 上午08:48:10
		//获得该员工该travelorder的BusinessTravelList
		return businessTravelListDao.get(travelorder);
	}
	
	/*
	 * @see com.cbts.service.travel.RoutesetService#submitRoute(java.util.List, java.lang.String, int, java.util.Date, java.util.Date)
	 */
	public boolean submitRoute(List<BusinessTravel> btlist, String userid, int standardId, Date startTime, Date endTime) {
		// zqd 上午08:48:10
		//新建一travellist
		try{
			BusinessTravelList list=new BusinessTravelList();
			TravelStandard ts=travelStandardDao.get(standardId);
			
			list.setStartTime(startTime);						//开始时间
			list.setEndTime(endTime);							//结束时间
			list.setUserInfoByUserid(userInfoDao.get(userid));	//员工
			String order=new SimpleDateFormat("yyyyMMdd-hhmmss").format(new Date()).concat("-").concat(userid);
			list.setTravelOrder(order);							//出差单号
			//list.setVerifierStatus("待报销");
			//其他为默认值，或者为空

			Double amount=0.0;
			//计算
			Double pperkm=ts.getTraffic().getPrice();		//每公里价格
			Double pperday=ts.getHotel().getPrice();		//每天的住宿费
			Double mealscost=ts.getMealsCost();
			Double elsecost=ts.getElseCost();
			for(BusinessTravel l: btlist){
				l.setSum(pperkm*l.getDistance()+pperday*l.getTime()+mealscost*l.getTime()+elsecost*l.getTime());	//计算该段的钱，运输费+住宿费+饮食费+其他费用
				amount+=l.getSum();							//总数增加
				l.setUserInfo(userInfoDao.get(userid));		//这里也要设定员工的信息
				l.setTravelStandard(ts);					//设定差旅标准信息
				l.setBusinessTravelList(list);				//设定travelOrder
			}
			list.setAmount(amount);							//设定总金额
			
			businessTravelListDao.save(list);				//提交出差列表数据
			
			businessTravelDao.saveList(btlist);				//将数据插入到数据库,提交路线

			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}
	
	/* 
	 * @see com.cbts.service.travel.RoutesetService#getBusinessTravelById(int)
	 */
	public BusinessTravel getBusinessTravelById(int infoId) {
		// zqd 下午10:17:15
		return businessTravelDao.get(infoId);
	}
	
	
	/*
	 * @see com.cbts.service.travel.RoutesetService#AccessUrl(java.lang.String, java.lang.String)
	 */
	public String accessUrl(String url, String postString) {
		// zqd 下午04:59:41
		String result = null;
		HttpURLConnection conn = null;
		try {
			URL postUrl = new URL(url);
			conn = (HttpURLConnection)postUrl.openConnection();
			conn.setRequestMethod("POST");				
			conn.setDoOutput(true);   
			conn.setDoInput(true);   
			conn.setUseCaches(false);
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");	//请求连接
			conn.setConnectTimeout(30000);
			conn.setReadTimeout(300000);
			//System.out.println("content：开始传递");
			OutputStream os = conn.getOutputStream();
			os.write(postString.getBytes("utf-8")); // 往远程URL传递参数			          
            os.flush();
            os.close();
            
            int code = conn.getResponseCode();
            //System.out.println("返回状态码："+code+", 返回长度："+conn.getContentLength());
            conn.getHeaderFields();
            conn.getContentLength();
            if(code==200){							//返回成功,接收数据
            	BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            	String line;
            	StringBuffer buffer = new StringBuffer();
            	while((line = reader.readLine()) != null) {
            		buffer.append(line);
            	}
            	result = buffer.toString();
            }else{
            	System.out.println("返回失败："+code);
            }
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	
}
